//
//  WLDownLoadCenter.m
//  WanLian
//
//  Created by 123456 on 2018/12/7.
//  Copyright © 2018 wanlian. All rights reserved.
//

#import "WLDownLoadCenter.h"
#import "WLFileUpDownLoadModel.h"
#import "HSDownloadManager.h"
#import "WLDataBaseManager.h"
#import "MonitorFlow.h"
#import "WLFileHandle.h"
#import "NSString+Ext.h"
#import "WLFileSocketManager.h"
#import "WLSocketWorker.h"
#import "WLLocalNotification.h"
@implementation WLDownLoadCenter


impl_single_instance(WLDownLoadCenter)
- (void)configure {
    
    NSArray *localTasks = [[WLDataBaseManager shareInstance] queryTotalListWithTableName:[WLFileUpDownLoadModel getTableNameWithModelType:WLDataBaseModelTypeDownload] className:[WLFileUpDownLoadModel class]];
    for (WLFileUpDownLoadModel *model in localTasks) {
        model.loadState = FileLoadingStateWaiting;
    }
    if (localTasks.count > 0) {
        [self.totalTaskArray addObjectsFromArray:localTasks];
    }
    
    self.currentTaskIndex = -1;
}

- (WLSocketWorker *)downloadTaskWithModel:(WLFileUpDownLoadModel *)model
                                       progress:(void (^)(float process))downloadProgress
                                        success:(void (^)(NSDictionary *successDict))success
                                        failure:(void (^)(NSString *errorMsg, NSInteger errorTag))failure
                                          error:(void (^)(NSError *error))err {

    WLFileSocketManager *socketManager = [WLFileSocketManager shareInstance];
    WLFileRequest *request = [model getRequestModel];
    request.host = [WLCommonTool getFileUpDownloadHost];
    request.port = 9002;
    WLSocketWorker *dataTask = [socketManager downloadTaskWithModel:request progress:^(float process, long expected, long loaded) {
        model.process = process;
        model.fileTotalBytes = expected;
        if (downloadProgress) {
            downloadProgress(process);
        }
    }  success:success failure:failure error:err];
    return dataTask;

}
//
//- (NSURLSessionDataTask *)downloadTaskWithModel:(WLFileUpDownLoadModel *)model
//                                       progress:(void (^)(float progress))downloadProgress
//                                        success:(void (^)(NSDictionary *successDict))success
//                                      failure:(void (^)(NSString *errorMsg, NSInteger errorTag))failure
//                                        error:(void (^)(NSError *error))err {
//
//    NSURLSessionDataTask *dataTask = [[HSDownloadManager sharedInstance] download:[WLCommonTool getRealURLWithUrlStr:model.requestURL] progress:^(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress) {
//        if (downloadProgress) {
//            downloadProgress(progress);
//        }
//    } state:^(DownloadState state) {
//        switch (state) {
//            case DownloadStateCompleted:
//                if (success) {
//                    success(nil);
//                }
//                break;
//            case DownloadStateFailed:
//                if (failure) {
//                    failure(@"", 0);
//                }
//                break;
//
//            default:
//                break;
//        }
//    }];
////    NSURLSessionDataTask *dataTask = nil;
////    if (model.fileType == SPFileTypeVideo) {
////        dataTask = [WLHttpManager WLBackgroundDownloadGet:model.requestURL parameters:nil progress:downloadProgress success:success failure:failure error:err inView:nil];
////    } else if (model.fileType == SPFileTypePhoto) {
////        dataTask = [WLHttpManager WLBackgroundDownloadGet:model.requestURL parameters:nil progress:downloadProgress success:success failure:failure error:err inView:nil];
////    }
//    return dataTask;
//
//}

- (WLSocketWorker *)startTaskWithModel:(WLFileUpDownLoadModel *)model
{
    [self startMonitor];
    model.loadState = FileLoadingStateRunning;
    
    self.currentTaskIndex = [self.totalTaskArray indexOfObject:model];
    WLWkSelf
    WLSocketWorker *dataTask = [self downloadTaskWithModel:model progress:^(float progress) {
        [self startMonitor];
        [weakSelf dealWithProcess:progress model:model];
    } success:^(NSDictionary *successDict) {
        [self stopMonitor];
        [weakSelf dealWithSuccess:successDict model:model];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf dealWithFailure:errorMsg errorTag:errorTag model:model];
    } error:^(NSError *error) {
        [weakSelf dealWithFailure:@"" errorTag:0 model:model];
    }];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.delegate && [self.delegate respondsToSelector:@selector(didStartTastWithIndex:)]) {//通知外部开始新的任务了
            [self.delegate didStartTastWithIndex:[self.totalTaskArray indexOfObject:model]];
        }
    });
    model.dataTask = dataTask;
    return dataTask;
}

- (void)dealWithProcess:(float)progress receivedSize:(NSInteger)receivedSize expectedSize:(NSInteger)expectedSize model:(WLFileUpDownLoadModel *)model {
    model.process = progress;
    if (self.delegate && [self.delegate respondsToSelector:@selector(dealWithProcess:receivedSize:expectedSize:index:)]) {
        [self.delegate dealWithProcess:progress receivedSize:receivedSize expectedSize:expectedSize index:[self.totalTaskArray indexOfObject:model]];
    }
}
- (void)dealWithSuccess:(NSDictionary *)successDict model:(WLFileUpDownLoadModel *)model {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.currentTaskIndex = -1;
        
        [self stopMonitor];
        model.fileURL = successDict[@"localURL"];
        model.localIdentifier = successDict[@"localIdentifier"];
        model.mediaLocalURL = successDict[@"localMediaURL"];
        model.comleteTime = [NSString getNowStrWithFormater:@"yyyy/MM/dd HH:mm"];
        [self deleteDataBaseWithModel:model];
        model.loadState = FileLoadingStateComplete;
        [self saveTaskToDataBaseWithModel:model];
        NSInteger index = [self.totalTaskArray indexOfObject:model];
        WLFileUpDownLoadModel *nextModel = nil;
        if (self.totalTaskArray.count > 1) {
            
            nextModel = (index < self.totalTaskArray.count - 1) ? [self.totalTaskArray objectAtIndex:index++] : self.totalTaskArray.firstObject;
        }
        
        [self.totalTaskArray removeObject:model];
        
        self.sucNum ++;
        [self checkShowCompleteAlert:model.isUpLoad];
        //    [self.uploadedArray insertObject:model atIndex:0];
        if (self.delegate && [self.delegate respondsToSelector:@selector(didCompleteTaskWithModel:)]) {
            [self.delegate didCompleteTaskWithModel:model];
        }
        
        if (nextModel && [self isTaskCanBeStart:nextModel]) {
            [self startTaskWithModel:nextModel];
        }
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kUpDownloadTaskCompleteNofication object:nil];
    });
}


//- (void)removeLocalFile:(WLFileUpDownLoadModel *)model {
//    
////    [[HSDownloadManager sharedInstance] deleteFile:[WLCommonTool getRealURLWithUrlStr:model.requestURL]];
//}
@end
